import React from 'react';
import './crmAddCrmUser.less';
import { Layout, Menu, Breadcrumb, Icon, Row, Col, Tag, DatePicker, Cascader, Button, Table, Checkbox, Modal, Input, Select, Form, Pagination, message } from 'antd';
import $ from 'jquery';
import Config from '../../../common/config';
import region from '../../../common/region';

const FormItem = Form.Item;
const config = new Config();
const { Header, Content, Footer, Sider } = Layout;
const Option = Select.Option;
const { RangePicker } = DatePicker;
const InputGroup = Input.Group;
const token = sessionStorage.getItem('token');

const UserInfo = JSON.parse(window.sessionStorage.getItem('UserInfo'));//当前操作人信息

const NewAddressForm = Form.create()(
    (props) => {
        const { onSubmit, form, region } = props;
        const { getFieldDecorator } = form;
        const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 16 } };
        return (
            <Form className="model-y-t">
                <FormItem {...formItemLayout} label="所在地区" >
                    {getFieldDecorator('area', {
                        rules: [{ required: true, type: 'array', message: '请选择收货地址所在的地区！' }],
                    })(
                        <Cascader options={region} placeholder="请选择省市区" />
                        )}
                </FormItem>
                <FormItem {...formItemLayout} label="详细地址" >
                    {getFieldDecorator('detail', {
                        initialValue: "",
                        validateTrigger: 'onBlur',
                        rules: [{
                            required: true, min: 3, max: 200, message: '请填写详细地址，长度在3到200个字符之间',
                        }],
                    })(
                        <Input type="textarea" rows={4} placeholder="建议您如实填写详细收货地址，例如街道名称，门牌号码，楼层和房间号等信息" style={{ resize: 'none' }} />
                        )}
                </FormItem>
                <FormItem {...formItemLayout} label="收货人姓名" >
                    {getFieldDecorator('name', {
                        initialValue: "",
                        validateTrigger: 'onBlur',
                        rules: [{
                            required: true, max: 20, message: '请填写收货人姓名，不超过20个字',
                        }]
                    })(
                        <Input placeholder="请输入收货人姓名" />
                        )}
                </FormItem>
                <FormItem {...formItemLayout} label="联系方式" >
                    {getFieldDecorator('phone', {
                        initialValue: "",
                        validateTrigger: 'onBlur',
                        rules: [{
                            required: true, pattern: /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/, message: '请填写正确格式的手机号码或固话号码',
                        }]
                    })(
                        <Input placeholder="请输入手机号码或固话号码" />
                        )}
                </FormItem>
                <FormItem className={"zhifu-btn"}>
                    <Button type="primary" style={{ marginLeft: 120, width: 100 }} onClick={onSubmit}>保存</Button>
                </FormItem>
            </Form>
        );
    }
);
class CrmAddCrmUserForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            userSourceList: [], //客户渠道数据列表
            managersList: [],//归属人数据列表
            userExistVisible: false, //直销客户已存在的情况的处理模态框
            userExistText: '', //直销客户已存在时显示的提示文本
            userRegVisible: false, //直销客户是商城会员的情况的处理模态框
            addressList: [], //地址列表
            addAddressVisible: false, //新增地址模态框的显示状态
            deleteAddressVisible: false, //删除地址模态框的显示状态
            editAddiressIndex: -1, //编辑的地址在地址列表中的索引
            deleteAddressIndex: -1,//删除的地址在地址列表中的索引
            addOrderVisible: false, //新增会员成功后的去下单处理模态框
            isPhoneData: [],//是否手机号数据
            ifShoppUser: 'N',//是否只存在于商城
            orderUserId: undefined,//会员ID,用于传值给新增订单页面
        }
    }

    componentDidMount() {
        this.getUserSourceList();
        this.getManagersList();
        this.handleRegion();
    }

    //加载客户渠道的数据列表
    getUserSourceList() {
        $.ajax({
            url: `${config.CrmSettings}/crm_customersource/BindSource`,
            type: "post",
            headers: { Authorization: 'Bearer ' + token },
            success: res => {
                if (res.code == 200) {
                    this.setState({
                        userSourceList: res.data,
                    });
                }
            }
        })
    }
    //加载客户归属人的数据列表
    getManagersList() {
        $.ajax({
            url: `${config.CrmDepartment}/department/deptree`,
            headers: { Authorization: 'Bearer ' + token },
            type: "post",
            data: {
                id: UserInfo.id
            },
            success: res => {
                if (res.code == 200) {
                    let managersList = [UserInfo].concat(res.userlist);
                    console.log('getManagersList', managersList)
                    this.setState({
                        managersList,
                    });
                }
            }
        })
    }
    //处理省市区数据
    handleRegion() {
        const setOptions = arr => {
            arr.map((item, key) => {
                item.value = item.name;
                item.label = item.name;
                if (item.child) {
                    item.children = item.child;
                    setOptions(item.children);
                }
            });
        }
        setOptions(region);
        this.setState({
            region
        });
    }

    //验证手机号对应的会员是否已经存在
    handlePhoneExist() {
        const { form } = this.props;
        form.validateFields(['phone'], (err, values) => {
            if (!err) {
                $.ajax({
                    url: `${config.CrmMember}/crm_user/isPhoneExist`,
                    headers: { Authorization: 'Bearer ' + token },
                    type: "post",
                    data: {
                        phone: values.phone,
                        userid: UserInfo.id,
                    },
                    success: res => {
                        console.log('isPhoneExist：', res)
                        if (res.code == 202) {//只存在于商城
                            this.setState({
                                userRegVisible: true,
                                isPhoneData: res,
                                ifShoppUser: 'Y',
                            });
                        } else if (res.code == 203) {//不存在该手机号
                            this.setState({
                                ifShoppUser: 'N',
                            }, () => {
                                this.props.form.validateFields((err, values) => {
                                    if (!err) {
                                        this.saveCRMMember();
                                    }
                                });
                            });
                        } else if (res.code == 204) {//已存在该手机号，且客户归属人为操作人本人或者其下级
                            this.setState({
                                userExistVisible: true,
                                ifShoppUser: 'N',
                                userExistText: '该账号已存在，请直接使用！'
                            });
                        } else if (res.code == 205) {//已存在该手机号，但客户归属人不是操作人本人或者其下级
                            this.setState({
                                userExistVisible: true,
                                ifShoppUser: 'N',
                                userExistText: `该账号归属人为${res.ManageUserName}！`
                            });
                        } else {
                            message.error('服务器繁忙，请稍后再试', 2);
                        }
                    }
                })
            } else {
                this.setState({
                    isPhoneData: [],
                    addressList: [],
                    ifShoppUser: 'N',
                }, () => {
                    this.props.form.setFieldsValue({
                        realname: '',
                        sex: '1',
                    });
                });
            }
        })
    }
    //处理已存在直销会员中的客户
    handleUserExist() {
        this.setState({
            userExistVisible: false,
            ifShoppUser: 'N',
            addressList: [],
        }, () => {
            this.props.form.setFieldsValue({
                phone: '',
                realname: '',
                sex: '1',
            });
        });
    }
    //处理已存在商城会员中的客户
    handleUserReg() {
        this.setState({
            userRegVisible: false,
        }, () => {
            const { isPhoneData, addressList } = this.state;
            console.log('是否存在于?商城的会员与地址数据：', isPhoneData);
            if (isPhoneData.shoppData) {
                this.props.form.setFieldsValue({
                    realname: isPhoneData.shoppData.realname,
                    sex: isPhoneData.shoppData.sex
                });
            }
            if (isPhoneData.shoppAddressData) {
                let newaddressList = isPhoneData.shoppAddressData;//addressList.concat(isPhoneData.shoppAddressData);
                this.setState({
                    addressList: newaddressList
                });
            }
        });
    }
    //取消处理已经存在商城会员中的客户
    cancelUserReg() {
        this.setState({
            userRegVisible: false,
            isPhoneData: [],
            addressList: [],
            ifShoppUser: 'N',
        }, () => {
            this.props.form.setFieldsValue({
                phone: '',
                realname: '',
                sex: '1'
            });
        });
    }

    //新增地址
    addAddress() {
        if (this.state.addressList.length === 10) {
            message.warning('您可以添加的地址上限为10条，不能再添加新地址了', 3);
        } else {
            this.setState({
                addAddressVisible: true,
                editAddiressIndex: -1,
            });
        }
    }
    //修改地址
    editAddiress(index) {
        const address = this.state.addressList[index];
        if (typeof address.area == 'string') {
            address.area = address.area.split(' ');
        }
        this.setState({
            addAddressVisible: true,
            editAddiressIndex: index,
        }, () => this.addressForm.setFieldsValue(address));
    }
    //取消保存地址
    cancelAddAddress() {
        this.addressForm.resetFields();
        this.setState({
            addAddressVisible: false
        });
    }
    //保存地址
    handleAddAddress() {
        this.addressForm.validateFields((err, values) => {
            if (!err) {
                const { addressList, editAddiressIndex } = this.state;
                if (addressList[editAddiressIndex]) {
                    addressList[editAddiressIndex] = values;
                } else {
                    addressList.push(values);
                }
                console.log('保存地址', addressList)
                this.setState({
                    addressList,
                    addAddressVisible: false
                });
                this.addressForm.resetFields();
            } else {
                message.error(`请正确填写必要的信息，再保存`, 2);
            }
        });
    }

    //删除地址
    deleteAddress(index) {
        this.setState({
            deleteAddressVisible: true,
            deleteAddressIndex: index
        });
    }
    //确认删除地址
    handleDeleteAddress() {
        let { addressList, deleteAddressIndex } = this.state;
        addressList.splice(deleteAddressIndex, 1);
        this.setState({
            addressList,
            deleteAddressVisible: false,
        });
    }
    //取消删除地址
    cancelDeleteAddress() {
        this.setState({
            deleteAddressVisible: false,
        });
    }

    //保存会员
    saveCRMMember() {
        const { form } = this.props;
        form.validateFields((err, values) => {
            if (!err) {
                const { addressList } = this.state;
                let ReceiveAddress = addressList.map((val, i) => {
                    return {
                        Addressid: val.id || 0,
                        Addressarea: typeof val.area == 'string' ? val.area.split(' ').join(' ') : val.area.join(' '),
                        Addressdetail: val.detail,
                        Addressname: val.name,
                        Addressphone: val.phone
                    }
                });
                values.ifShoppUser = this.state.ifShoppUser;//是否只属于商城会员 Y or N
                values.ceateuserid = UserInfo.userid;//UserInfo.id;
                values.ReceiveAddress = JSON.stringify(ReceiveAddress);
                console.log(values);
                $.ajax({
                    url: `${config.CrmMember}/crm_user/AddCrmUser`,
                    headers: { Authorization: 'Bearer ' + token },
                    type: "post",
                    data: values,
                    success: res => {
                        console.log(res)
                        if (res.code == 200) {
                            message.success(res.mes, 2);
                            form.resetFields();
                            this.setState({
                                addressList: [],
                                addOrderVisible: true,
                                ifShoppUser: 'N',
                                orderUserId: res.orderUserId
                            });
                        } else {
                            message.error('服务器繁忙，请稍后再试', 2);
                        }
                    }
                })
            } else {
                message.error('请正确填写必要的信息，再提交', 2);
            }
        })
    }
    //新增会员成功后直接去下订单
    handleAddOrder() {
        const { orderUserId } = this.state;
        window.location.hash = `/crmSetOrder/${orderUserId}`;
    }
    //新增会员成功后取消去下订单，继续新增会员
    cancelAddOrder() {
        this.setState({
            addOrderVisible: false,
            isPhoneData: [],
            addressList: [],
            orderUserId: undefined,
        }, () => {
            this.props.form.setFieldsValue({
                phone: '',
                realname: '',
                sex: '1',
                ifShoppUser: 'N',
            });
        });
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const { userSourceList, managersList, addressList } = this.state;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
            },
        };
        const formItemLayoutyt = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 2 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 20 },
            },
        };
        const userSourceOptions = userSourceList.map((val) => {
            return <Option key={val.id} value={val.id.toString()}>{val.sourcename}</Option>
        });
        const managersOptions = managersList.map((val) => {
            return <Option key={val.id} value={val.userid}>{val.username}</Option>
        });
        return (
            <Form>
                <div className='goods-label'>
                    <div className='goods-label-cont clearfix'>
                        <div className='goods-label-cont-nav clearfix'>
                            <Breadcrumb separator=">">
                                <Breadcrumb.Item>直销管理</Breadcrumb.Item>
                                <Breadcrumb.Item>会员管理</Breadcrumb.Item>
                                <Breadcrumb.Item>新增/修改会员信息</Breadcrumb.Item>
                            </Breadcrumb>
                        </div>

                        {/* 客户基本信息 */}
                        <div className='acmilan'>
                            <h1>
                                <span>客户信息</span>
                            </h1>
                            <Row>
                                <Col span={8}>
                                    <FormItem {...formItemLayout} label="手 机 号" >
                                        {getFieldDecorator('phone', {
                                            initialValue: "",
                                            validateTrigger: 'onBlur',
                                            rules: [{ required: true, whitespace: true, len: 11, pattern: /^(1[34578]\d{9})$/, message: "请填写客户正确的手机号" }],
                                        })(
                                            <Input autoFocus placeholder="请输入手机号" onBlur={() => this.handlePhoneExist()} />
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem {...formItemLayout} label="创 建 人">
                                        <p>{UserInfo.username}</p>
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem {...formItemLayout} label="归 属 人">
                                        {getFieldDecorator('manageuserid', {
                                            initialValue: UserInfo.userid
                                        })(
                                            <Select>{managersOptions}</Select>
                                            )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={8}>
                                    <FormItem {...formItemLayout} label="姓 名" >
                                        {getFieldDecorator('realname', {
                                            initialValue: "",
                                            validateTrigger: 'onBlur',
                                            rules: [{ required: true, whitespace: true, max: 20, message: "请填写客户的姓名，不多于20个字" }],
                                        })(
                                            <Input placeholder="请输入客户姓名" />
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem {...formItemLayout} label="性 别">
                                        {getFieldDecorator('sex', {
                                            rules: [{ required: true }], initialValue: "1"
                                        })(
                                            <Select>
                                                <Option value="1">男</Option>
                                                <Option value="0">女</Option>
                                                <Option value="2">保密</Option>
                                            </Select>
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem {...formItemLayout} label="客户渠道">
                                        {getFieldDecorator('customersourceid', {
                                            rules: [{ required: true, message: "请选择客户渠道" }],
                                            initialValue: userSourceList.length > 0 ? userSourceList[0].id.toString() : ''
                                        })(
                                            <Select>{userSourceOptions}</Select>
                                            )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={8}>
                                    <FormItem {...formItemLayout} label="微 信 号" >
                                        {getFieldDecorator('wxid', {
                                            initialValue: "",
                                            validateTrigger: 'onBlur',
                                            rules: [{ max: 20, message: "微信号不能多于20个字" }],
                                        })(
                                            <Input placeholder="请输入微信号" />
                                            )}
                                    </FormItem>
                                </Col>
                                <Col span={8}>
                                    <FormItem {...formItemLayout} label="客户状态">
                                        {getFieldDecorator('customerstatus', {
                                            initialValue: "1"
                                        })(
                                            <Select>
                                                <Option value="1">成交</Option>
                                                <Option value="2">意向客户</Option>
                                            </Select>
                                            )}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={24}>
                                    <FormItem {...formItemLayoutyt} label="客户需求">
                                        {getFieldDecorator('remark', {
                                            initialValue: "",
                                            validateTrigger: 'onBlur',
                                            rules: [{ max: 500, message: "客户需求不能多于500个字" }],
                                        })(
                                            <Input type="textarea" rows={3} placeholder="请输入客户需求，不多于500个字" style={{ resize: "none" }} />
                                            )}
                                    </FormItem>
                                </Col>
                            </Row>
                        </div>

                        {/* 收货地址 */}
                        <div className='acmilan' style={{ marginTop: 30 }}>
                            <h1>收货地址
                                <a className='member-button-tgd' onClick={() => this.addAddress()} style={{ marginLeft: 20, width: 65, background: '#798594' }}><Icon type="plus" />新增</a>
                            </h1>
                            {/* 地址列表 */}
                            {
                                addressList.map((item, index) => {
                                    return <div className='caotuht' key={index}>
                                        <Row>
                                            <Col span={4}>收货人：{item.name}</Col>
                                            <Col span={4}>手机号码：{item.phone}</Col>
                                            <Col span={10}>所在地区：{typeof (item.area) == 'string' ? item.area.split(' ').join('') + item.detail : item.area.join('') + item.detail}</Col>
                                            <Col span={6}>
                                                <a onClick={() => this.editAddiress(index)} className="member-button-tgd-a" style={{ marginRight: 20 }}>修改</a>
                                                <a onClick={() => this.deleteAddress(index)} className="member-button-tgd-a">删除</a>
                                            </Col>
                                        </Row>
                                    </div>
                                })
                            }
                            {/* 新增收货地址 */}
                            <Modal
                                title="新增收货地址 打红色*为必填项"
                                visible={this.state.addAddressVisible}
                                onCancel={() => this.cancelAddAddress()}
                                footer={null}
                                maskClosable={false}
                            >
                                <div className='baoigg'>
                                    <NewAddressForm
                                        ref={(form) => this.addressForm = form}
                                        onSubmit={this.handleAddAddress.bind(this)}
                                        region={region}
                                    />
                                </div>
                            </Modal>
                            {/* 删除收货地址 */}
                            <Modal
                                title="删除收货地址"
                                visible={this.state.deleteAddressVisible}
                                onOk={() => this.handleDeleteAddress()}
                                onCancel={() => this.cancelDeleteAddress()}
                                maskClosable={false}
                            >
                                <div className='delets_gg'>
                                    <p className='delets_gg1'>温馨提示</p>
                                    <p>删除后不可恢复，是否继续删除？</p>
                                </div>
                            </Modal>
                        </div>

                        {/* 手机号对应客户已经存在直销会员中 */}
                        <Modal visible={this.state.userExistVisible} footer={null} closable={false} maskClosable={false}>
                            <div className='delets_gg'>
                                <p className='delets_gg1'>{this.state.userExistText}</p>
                                <a className='member-button-tgd' onClick={() => this.handleUserExist()}>关闭</a>
                            </div>
                        </Modal>

                        {/* 手机号对应客户在商城已经注册*/}
                        <Modal visible={this.state.userRegVisible} closable={false} maskClosable={false}
                            onOk={() => this.handleUserReg()} onCancel={() => this.cancelUserReg()}
                        >
                            <div className='delets_gg'>
                                <p>该账号已是商城会员，是否合并会员？</p>
                            </div>
                        </Modal>

                        {/* 新增会员成功后的处理模态框*/}
                        <Modal visible={this.state.addOrderVisible} closable={false} maskClosable={false}
                            onOk={() => this.handleAddOrder()} onCancel={() => this.cancelAddOrder()}
                        >
                            <div className='delets_gg'>
                                <p className='delets_gg1'>保存成功</p>
                                <p>是否现在去给该客户下单？</p>
                            </div>
                        </Modal>
                        <a className='member-button-tgd' onClick={(e) => this.saveCRMMember()} style={{ marginRight: 60, float: "right", marginTop: 60, width: 100, height: 35, lineHeight: '35px', fontSize: 14, fontWeight: 'bold' }}>保存</a>
                    </div>
                </div>
            </Form >
        )
    }
}

const CrmAddCrmUser = Form.create()(CrmAddCrmUserForm);
export default CrmAddCrmUser;